import { useStore } from "../store";
import router from "../router/index";
const store = useStore();

const ajax = function (url, options = {}) {
    const {
        method = 'GET',
        data = null,
        headers = {},
        responseType = 'json'
    } = options;

    // 自动识别 FormData 类型
    const isFormData = data instanceof FormData;
    
    const config = {
        method: method.toUpperCase(),
        headers: {
            // 仅非 FormData 时设置默认 Content-Type
            ...(!isFormData && { 'Content-Type': 'application/json' }),
            'token': store.token || '',
            ...headers
        }
    };

    // GET 请求处理 URL 参数
    if (method.toUpperCase() === 'GET' && data) {
        const params = new URLSearchParams(data).toString();
        url += (url.includes('?') ? '&' : '?') + params;
    } 
    // 非 GET 请求处理请求体
    else if (data) {
        config.body = isFormData ? data : JSON.stringify(data);
    }
    return new Promise((resolve, reject) => {
        fetch(url, config)
            .then(async response => {
                // 统一错误处理
                if (!response.ok) {
                    const error = new Error(`HTTP error! status: ${response.status}`);
                    error.status = response.status;
                    try {
                        error.data = await response.clone().json();
                    } catch {
                        error.data = await response.clone().text();
                    }
                    throw error;
                }

                // 处理不同响应类型
                switch (responseType) {
                    case 'json': 
                        return response.json();
                    case 'text':
                        return response.text();
                    case 'blob': {
                        const blob = await response.blob();
                        return {
                            blob,
                            filename: decodeURIComponent(
                                response.headers.get('Content-Disposition')?.split('filename=')[1] || ''
                            )
                        };
                    }
                    case 'arrayBuffer':
                        return response.arrayBuffer();
                    default:
                        return response.json();
                }
            })
            .then(data => {
                // 自定义业务状态码处理
                console.log('请求成功:', { url, method, data });
                if (data.code === -1) {
                    return reject(data.msg|| '异常');
                }
                resolve(data);
            })
            .catch(error => {
                console.error('请求失败:', {
                    url,
                    method,
                    error: error.message,
                    status: error.status,
                    data: error.data
                });
                if(error.status === 401) {
                    store.setToken(null);
                    router.push('/login');
                }
                reject(error);
            });
    });
};

export default ajax;